package com.anxin.security.service;

import com.anxin.common.enums.RoleEnum;
import com.anxin.common.enums.UserStatusEnum;
import com.anxin.entity.SysUser;
import com.anxin.mapper.SysUserMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final SysUserMapper userMapper;

    public CustomUserDetailsService(SysUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userMapper.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        if (user.getStatus() == UserStatusEnum.DISABLED.getValue()) {
            throw new UsernameNotFoundException("用户已禁用: " + username);
        }

        if (user.getRoleId() == RoleEnum.PATIENT.getCode()) {
            List<SimpleGrantedAuthority> authorities = List.of(new SimpleGrantedAuthority("ROLE_" + RoleEnum.PATIENT.getAuthority()));
            return new User(user.getUsername(), user.getPassword(), authorities);
        } else {
            // 获取用户角色和权限
            List<String> roles = userMapper.getUserRoles(user.getId());
            List<String> permissions = userMapper.getUserPermissions(user.getId());

            // 创建权限列表
            List<SimpleGrantedAuthority> authorities = roles.stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                    .collect(Collectors.toList());

            // 添加权限
            permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .forEach(authorities::add);
            return new User(user.getUsername(), user.getPassword(), authorities);
        }
    }
}
